package licode.unisop.platform.application.executor;

import licode.unisop.platform.application.exception.PlatErrorCode;
import licode.unisop.platform.client.cache.PlatAuthCache;
import licode.unisop.platform.client.vo.PlatAuthVO;
import licode.unisop.platform.domain.PlatAuthItem;
import licode.unisop.platform.domain.PlatAuthManager;
import licode.unisop.provider.info.SiPlatIdFind;
import licode.unisop.provider.utils.StrUtil;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 内存缓存平台实现
 *
 * @author licode
 */
@Component
public class PlatAuthCacheMemory implements PlatAuthCache, PlatAuthManager {
    private final ConcurrentHashMap<String, PlatAuthItem> platforms = new ConcurrentHashMap<>();

    @Override
    public PlatAuthVO getPlatformById(SiPlatIdFind idInfo) {
        PlatAuthItem item;
        if (null == idInfo) {
            throw PlatErrorCode.PLATFORM_NOT_AUTH.buildThrow();
        }
        item = findPlatAuthItem(idInfo);

        return null == item ? null : item.getPlatformAuth();
    }

    @Override
    public void updatePlatform(PlatAuthVO plInfo) {
        PlatAuthItem item;
        item = findPlatAuthItem(SiPlatIdFind.builder()
                .platformId(plInfo.getPlatformId())
                .build());
        if (null != item) {
            item.setPlatformAuth(plInfo);
        }
    }

    @Override
    public int getAuthCount() {
        return platforms.size();
    }

    @Override
    public List<PlatAuthVO> getAuthPlatforms() {
        return platforms.values().stream()
                .map(PlatAuthItem::getPlatformAuth)
                .collect(Collectors.toList());
    }

    @Override
    public PlatAuthItem findPlatAuthItem(SiPlatIdFind idInfo) {
        return platforms.get(keyFromPlatIdInfo(idInfo));
    }

    @Override
    public void updatePlatAuthItem(PlatAuthItem authItem) {
        SiPlatIdFind idInfo = SiPlatIdFind.builder()
                .platformId(authItem.getPlatform().getId())
                .build();
        String key = keyFromPlatIdInfo(idInfo);
        platforms.put(key, authItem);
    }

    @Override
    public void removePlatAuthItem(SiPlatIdFind idInfo) {
        platforms.remove(keyFromPlatIdInfo(idInfo));
    }

    public String keyFromPlatIdInfo(SiPlatIdFind idInfo) {
        String platId = idInfo.getPlatformId();
        return StrUtil.isBlank(platId) ? "" : platId;
    }
}
